/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
    vector<vector<int>> pathSum(TreeNode *root, int targetSum)
    {
        if (root == nullptr)
        {
            return {};
        }
        vector<vector<int>> result;
        vector<TreeNode *> path{root};
        vector<int> pathVal{root->val};
        inorder(root->val, targetSum, path, pathVal, result);
        return result;
    }

    void inorder(int pathSum, int targetSum, vector<TreeNode *> &path, vector<int> &pathVal, vector<vector<int>> &result)
    {
        TreeNode *node = path.back();
        if (node->left == nullptr && node->right == nullptr)
        {
            if (pathSum == targetSum)
            {
                result.push_back(pathVal);
            }
            return;
        }
        if (node->left != nullptr)
        {
            path.push_back(node->left);
            pathVal.push_back(node->left->val);
            pathSum += node->left->val;
            inorder(pathSum, targetSum, path, pathVal, result);
            path.pop_back();
            pathVal.pop_back();
            pathSum -= node->left->val;
        }
        if (node->right != nullptr)
        {
            path.push_back(node->right);
            pathVal.push_back(node->right->val);
            pathSum += node->right->val;
            inorder(pathSum, targetSum, path, pathVal, result);
            path.pop_back();
            pathVal.pop_back();
            pathSum -= node->right->val;
        }
    }
};